package com.example.fivechessonline;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.app.ActivityCompat;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.fivechessonline.bean.ChessTable;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HallActivity2 extends AppCompatActivity {
    private static final String TAG=HallActivity2.class.getSimpleName();
    private Runnable updataRunnable;
    private transient boolean stopFlag=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hall2);
        updataRunnable = new Runnable() {
            @Override
            public void run() {
                while(!stopFlag) {
                    setupHall();
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }
    @Override
    protected void onResume() {
        super.onResume();
        stopFlag= false;
        new Thread(updataRunnable).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopFlag = true;

    }
    private void sitDownAgain(final ChessTable chessTable,Button button,String s){
        button.setBackground(ActivityCompat.getDrawable(getApplicationContext(), R.drawable.loading));
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), ChessActivity2.class);
                intent.putExtra("tableId", chessTable.getId());
                intent.putExtra("blackOrWhite",s);
                startActivity(intent);
            }
        });
    }
    private void sitDown(final ChessTable chessTable,String s) {
        String url = "https://fivechess.tzchenyu.com/join_table/" + chessTable.getId() + "/" + s;

        final  Request request = new Request.Builder().url(url).build();
        MainActivity.client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Intent intent = new Intent(getApplicationContext(), ChessActivity2.class);
                intent.putExtra("tableId", chessTable.getId());
                intent.putExtra("blackOrWhite",s);
                startActivity(intent);
            }
        });
    }
    private void setupHall(){
        String url ="https://fivechess.tzchenyu.com/chess_table";

        Request request = new Request.Builder().url(url).build();
        MainActivity.client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e){
                Looper.prepare();
                Toast.makeText(getApplicationContext(), "Error in get chess table",Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException{
                SharedPreferences sp=getSharedPreferences("user",MODE_PRIVATE);
                int userId= sp.getInt("id",0);
                String content=response.body().string();
                Log.i(TAG,content);
                Gson gson = new Gson();
                ChessTable[] chessTables=gson.fromJson(content,ChessTable[].class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LinearLayout oneLine=null;

                        LinearLayout linearLayout=findViewById(R.id.hall);
                        linearLayout.removeAllViews();
                        for (int i=0;i<chessTables.length;i++){
                            if(i%2==0) {
                                oneLine = new LinearLayout(getApplicationContext());
                                oneLine.setOrientation(LinearLayout.HORIZONTAL);
                                linearLayout.addView(oneLine);
                            }
                            ChessTable chessTable =chessTables[i];
                            View view = getLayoutInflater().inflate(R.layout.table,null);
                            Button blackButton;
                            Button whiteButton;
                            blackButton=((Button) view.findViewById(R.id.black));
                            whiteButton=((Button) view.findViewById(R.id.white));
                            if(chessTable.getUserBlack()>0) {
                                blackButton.setBackground(ActivityCompat.getDrawable(getApplicationContext(), R.drawable.user));
                                if (chessTable.getUserBlack()==userId){
                                    sitDownAgain(chessTable,blackButton,"black");
                                }
                            }else{
                                blackButton.setBackground(ActivityCompat.getDrawable(getApplicationContext(), R.drawable.down));
                                blackButton.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sitDown(chessTable,"black");
                                    }
                                });
                            }
                            if(chessTable.getUserWhite()>0){
                                whiteButton.setBackground(ActivityCompat.getDrawable(getApplicationContext(), R.drawable.user));
                                if (chessTable.getUserWhite()==userId){
                                    sitDownAgain(chessTable,whiteButton,"white");
                                }
                            }else {
                                whiteButton.setBackground(ActivityCompat.getDrawable(getApplicationContext(), R.drawable.down));
                                whiteButton.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sitDown(chessTable,"white");
                                    }
                                });
                            }
                            oneLine.addView(view);
                        }
                    }
                });

            }
        });
    }
}